﻿using BandiZipBatch.Properties;
using System;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace BandiZipBatch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
        }

        private void btnUnzip_Click(object sender, EventArgs e)
        {
            //判断是否存在bandizip程序
            var validateText = Execute("bz.exe", 0);
            if (string.IsNullOrEmpty(validateText))
            {
                MessageBox.Show(Resources.NotInstall);
                return;
            }
            //判断是否选择待解压文件夹
            if (string.IsNullOrEmpty(this.txtWaitUnzip.Text))
            {
                MessageBox.Show(Resources.UnZipFolder);
                return;
            }
            //判断是否选择了解压到某个文件夹或是解压到同一文件夹
            if (string.IsNullOrEmpty(this.txtTargeFolder.Text) && !this.cbSameCatalogue.Checked)
            {
                MessageBox.Show(Resources.IsSameDirectory);
                return;
            }
            //判断是否选择了压缩文件类型
            if (!CheckCompressedFormatIsChecked())
            {
                MessageBox.Show(Resources.FileType);
                return;
            }
            //构造命令
            var command = $"Bandizip.exe x {(this.cbDelSrc.Checked ? "-delsrc" : string.Empty)} -o:{(this.cbSameCatalogue.Checked ? this.txtWaitUnzip.Text : this.txtTargeFolder.Text)} {(this.cbSameFolder.Checked ? "-target:name" : string.Empty)} {(!string.IsNullOrEmpty(this.txtPassword.Text) ? "-p:" + this.txtPassword.Text : string.Empty)} {this.txtWaitUnzip.Text + "\\*." + (this.rb7z.Checked ? rb7z.Text : rbRar.Checked ? rbRar.Text : rbZip.Text)}";
            //执行命令
            Execute(command, 0);
        }

        /// <summary>
        /// 判断是否选择了压缩文件类型
        /// </summary>
        /// <returns></returns>
        private bool CheckCompressedFormatIsChecked()
        {
            return Controls.OfType<RadioButton>().Select(item => item as RadioButton).Any(rb => rb.Checked);
        }

        #region 打开选择文件框
        private void txtWaitUnzip_Enter(object sender, EventArgs e)
        {
            this.fbdFolderChoose.ShowDialog();
            this.txtWaitUnzip.Text = this.fbdFolderChoose.SelectedPath;
        }

        private void txtTargetFolder_Enter(object sender, EventArgs e)
        {
            this.fbdFolderChoose.ShowDialog();
            this.txtTargeFolder.Text = this.fbdFolderChoose.SelectedPath;
        }
        #endregion
        
        private void cbSameCatalogue_CheckedChanged(object sender, EventArgs e)
        {
            //如果选择了解压至同一文件夹，那么解压至某一目录则不可用，并把内容置空
            this.txtTargeFolder.Enabled = !this.cbSameCatalogue.Checked;
            this.txtTargeFolder.Text = string.Empty;
        }

        /// <summary>  
        /// 执行DOS命令，返回DOS命令的输出  
        /// </summary>  
        /// <param name="command">dos命令</param>
        /// <param name="seconds">等待命令执行的时间 如果设定为0，则无限等待</param>
        /// <returns>返回DOS命令的输出</returns>  
        private static string Execute(string command, int seconds)
        {
            var output = string.Empty; //输出字符串  
            if (command == null || command.Equals("")) return output;
            var process = new Process();//创建进程对象  
            var startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe", //设定需要执行的命令  
                Arguments = "/C " + command, //“/C”表示执行完命令后马上退出  
                UseShellExecute = false, //不使用系统外壳程序启动 
                RedirectStandardInput = false, //不重定向输入  
                RedirectStandardOutput = true, //重定向输出  
                CreateNoWindow = true //不创建窗口  
            };
            process.StartInfo = startInfo;
            try
            {
                if (process.Start())//开始进程  
                {
                    if (seconds == 0)
                    {
                        process.WaitForExit();//这里无限等待进程结束  
                    }
                    else
                    {
                        process.WaitForExit(seconds); //等待进程结束，等待时间为指定的毫秒  
                    }
                    output = process.StandardOutput.ReadToEnd();//读取进程的输出  
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);//捕获异常，输出异常信息
            }
            finally
            {
                process.Close();
            }
            return output;
        }
        
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //打开链接
            Process.Start(this.linkLabel1.Text);
        }
    }
}
